﻿package com.example.smartpillow;

import ioio.lib.api.AnalogInput;
import ioio.lib.api.exception.ConnectionLostException;
import ioio.lib.util.BaseIOIOLooper;
import ioio.lib.util.IOIOLooper;
import ioio.lib.util.android.IOIOActivity;

import java.text.DecimalFormat;
import java.text.FieldPosition;
import java.text.Format;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.Random;
import java.util.TimeZone;

import com.androidplot.xy.LineAndPointFormatter;
import com.androidplot.xy.SimpleXYSeries;
import com.androidplot.xy.XYPlot;
import com.androidplot.xy.XYSeries;
import com.androidplot.xy.XYStepMode;
import com.example.smartpillow.TempDisplay.Looper;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.PopupMenu;
import android.widget.PopupMenu.OnMenuItemClickListener;
import android.widget.TextView;
import android.widget.Toast;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Shader;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.widget.ImageButton;


public class MainActivity extends IOIOActivity implements OnMenuItemClickListener, OnClickListener{
	
        private XYPlot plot1;
    	private Random random;
    	private TextView tempDisplay;
    	private TextView alarmDisplay;
    	private final static int item1 = 1;
        private final static int item2 = 2;
        private final static int item3 = 3;
        
        //variables used for alarm are here
        public boolean tempboo= true;   		   	
        ImageButton btnStart;
        Context context;
        static PendingIntent pendingIntent;
        static AlarmManager alarm;
    	
    	
        /* (non-Javadoc)
         * @see android.app.Activity#onCreate(android.os.Bundle)
         */
        @Override
        protected void onCreate(Bundle savedInstanceState) {
        	
            super.onCreate(savedInstanceState);
            this.requestWindowFeature(Window.FEATURE_NO_TITLE);
            setContentView(R.layout.activity_main);
            
           	
       		
       	
            
            tempDisplay = (TextView) findViewById(R.id.textView1);
            alarmDisplay = (TextView) findViewById(R.id.alarmview);
            
            plot1 = (XYPlot)findViewById(R.id.plot1);
            
            
            MySqlDatabase sql = new MySqlDatabase(getBaseContext());
            
            sql.sqlInsert(32);
            sql.sqlInsert(35);
            sql.sqlInsert(34);
           
            
            Map<Long, Double> sqlmap = sql.sqlQuery();
            XYSeries series1 = new SimpleXYSeries(new ArrayList<Long>(sqlmap.keySet()), new ArrayList<Double>(sqlmap.values()),"℃");
            //plot1.setTicksPerRangeLabel(8);
            //plot1.setTicksPerDomainLabel(7);

            plot1.getGraphWidget().getGridBackgroundPaint().setColor(Color.TRANSPARENT);
            plot1.getGraphWidget().getBackgroundPaint().setColor(Color.TRANSPARENT);
            plot1.getBackgroundPaint().setColor(Color.TRANSPARENT);
            plot1.getBorderPaint().setColor(Color.TRANSPARENT);
           
            plot1.getGraphWidget().getDomainGridLinePaint().setColor(Color.DKGRAY);
            plot1.getGraphWidget().getDomainGridLinePaint().
                    setPathEffect(new DashPathEffect(new float[]{1, 1}, 1));
            
            plot1.getGraphWidget().getRangeGridLinePaint().setColor(Color.DKGRAY);
            plot1.getGraphWidget().getRangeGridLinePaint().
                    setPathEffect(new DashPathEffect(new float[]{1, 1}, 1));
            
            plot1.getGraphWidget().getDomainOriginLinePaint().setColor(Color.BLACK);
            plot1.getGraphWidget().getRangeOriginLinePaint().setColor(Color.BLACK);
            
            plot1.getGraphWidget().getRangeLabelPaint().setTextSize(25);
            plot1.getGraphWidget().getDomainLabelPaint().setTextSize(25);
            
            plot1.getGraphWidget().getRangeLabelPaint().setColor(Color.BLUE);
            plot1.getGraphWidget().getDomainLabelPaint().setColor(Color.BLUE);
            
            
            
            
            Paint lineFill = new Paint();
            
            
            // a View from within onCreate.  one alternative is to specify a dimension in resources
            // and use that accordingly.  at least then the values can be customized for the device type and orientation.
            Shader shader = new Shader();
            //lineFill.setShader(new LinearGradient(0, 0, 0, 0, Color.TRANSPARENT, Color.WHITE, Shader.TileMode.MIRROR));
            //BarFormatter formatter = new BarFormatter(Color.BLUE, Color.TRANSPARENT);
            lineFill.setAlpha(200);
            lineFill.setShader(new LinearGradient(0, 0, 0, 300, Color.WHITE, Color.WHITE, Shader.TileMode.MIRROR));
            LineAndPointFormatter formatter  =
                    new LineAndPointFormatter(Color.BLACK, Color.YELLOW, Color.WHITE, null);
            
            
            formatter.setFillPaint(lineFill);
            plot1.getGraphWidget().setPadding(5, 18, 20, 15);
            plot1.getGraphWidget().setGridPaddingLeft(5);
            plot1.getGraphWidget().setGridPaddingTop(5);
            plot1.getGraphWidget().setGridPaddingRight(5);
            plot1.getGraphWidget().setGridPaddingBottom(5);
            plot1.addSeries(series1, formatter);
                    
            plot1.setDomainStep(XYStepMode.SUBDIVIDE, sqlmap.keySet().size());
            plot1.setRangeStep(XYStepMode.SUBDIVIDE, 5);

            // customize our domain/range labels
            plot1.setDomainLabel("Time");
            plot1.setRangeLabel("Temperature (℃)");
            plot1.getGraphWidget().getRangeLabelPaint().setTextSize(25);
            plot1.getGraphWidget().getDomainLabelPaint().setTextSize(25);
            
            
            plot1.setRangeValueFormat(new DecimalFormat("0.#"));

            plot1.setDomainValueFormat(new Format() {
            	private SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
            	

                @Override
                public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {

                    // because our timestamps are in seconds and SimpleDateFormat expects milliseconds
                    
                	dateFormat.setTimeZone(TimeZone.getTimeZone("GMT+8"));
                    long timestamp = ((Number) obj).longValue() ;
                    Date date = new Date(timestamp);
                    
                    return dateFormat.format(date, toAppendTo, pos);
                }

                @Override
                public Object parseObject(String source, ParsePosition pos) {
                    return null;

                }
                
                
            });
            
    		Intent intentsOpen = new Intent(this, AlarmReceiver.class);
    		intentsOpen.setAction(".ACTION");
    		pendingIntent = PendingIntent.getBroadcast(this,111, intentsOpen, 0);
    		alarm = (AlarmManager) getSystemService(ALARM_SERVICE);


    		btnStart=(ImageButton)findViewById(R.id.alarm);		
    		btnStart.setOnClickListener(this);
            
            		
            
            sql.sqlInsert(30);
            sql.sqlInsert(35);
            sql.sqlInsert(36);
            

          
            /*
             * create popup menu
             */

            ImageButton button4 = (ImageButton) findViewById(R.id.cloudboy);
          	 button4.setOnClickListener(new OnClickListener(){
          	 @Override
                  public void onClick(View v){
          		showPopup(v);
          		
          	  }
          	 });
          	
               }
              
              public void showPopup(View v){ //display popup on click
                  
              	PopupMenu popupMenu = new PopupMenu(this,v);    	
              	popupMenu.setOnMenuItemClickListener(this);
                  popupMenu.getMenu().add(Menu.NONE, item1, Menu.NONE, "Sensor Test");
                  //popupMenu.getMenu().add(Menu.NONE, item2, Menu.NONE, "Credits");
                  //popupMenu.getMenu().add(Menu.NONE, item3, Menu.NONE, "Help");

                  popupMenu.setOnMenuItemClickListener(this);

                  //findViewById(R.id.button4).setOnClickListener(this);
              	
              	//popupMenu.setOnDismissListener(this);    	
              	//popupMenu.inflate(R.menu.popup_menu);
              	popupMenu.show();
              	
              }


          	public boolean onMenuItemClick(MenuItem item) {
          		
          		switch(item.getItemId()){
          		
          		case item1:
          			Toast.makeText(this, "Sensor Test Clicked", 
                  	Toast.LENGTH_SHORT).show();                 			
                  	Intent gotoSensor = new Intent (MainActivity.this, TempDisplay.class);
                  	startActivity(gotoSensor);
                  	return true;
         		/*case item2: //does not work for these few items even though code is simple
          			Toast.makeText(this, "Credits Clicked", 
          			Toast.LENGTH_SHORT).show();
          			Intent gotoCredits = new Intent (MainActivity.this, Credits.class);
          			startActivity(gotoCredits);
          			return true;
          		case item3:
          			Intent gotoHelp = new Intent (MainActivity.this, Help.class);
          			startActivity(gotoHelp);

          			Toast.makeText(this, "Help Clicked", 
          			Toast.LENGTH_SHORT).show();
          			return true;*/
          		
          		default:			
          			return false;			
          		}	

    }
        
        /* Temperature reading is done here
         * and displayed in a textbox in main activity
         */
        
        class Looper extends BaseIOIOLooper{
        	
        	private AnalogInput tempFromPin1_;
        	private AnalogInput tempFromPin2_;
        	private AnalogInput tempFromPin3_;
        	private AnalogInput tempFromPin4_;
        	private AnalogInput tempFromPin5_;
        	private int boardPin1=41;
        	private int boardPin2=42;
        	private int boardPin3=43;
        	private int boardPin4=44;
        	private int boardPin5=45;
        	private float getVoltage1;
        	private float getVoltage2;
        	private float getVoltage3;
        	private float getVoltage4;
        	private float getVoltage5;
        	public  float temp1 = (float)0.00;
        	public  float temp2 = (float)0.00;
        	public  float temp3 = (float)0.00;
        	public  float temp4 = (float)0.00;
        	public  float temp5 = (float)0.00;
        	private float maxTemptemp = 0;
        	
        	@Override
        	protected void setup() throws ConnectionLostException{
        		
        		tempFromPin1_=ioio_.openAnalogInput(boardPin1);
        		tempFromPin2_=ioio_.openAnalogInput(boardPin2);
        		tempFromPin3_=ioio_.openAnalogInput(boardPin3);
        		tempFromPin4_=ioio_.openAnalogInput(boardPin4);
        		tempFromPin5_=ioio_.openAnalogInput(boardPin5);
        	}
        	
        	@Override
			public void loop() throws ConnectionLostException{
        		
        		
        		try{
        			Thread.sleep(5000);
        			getVoltage1=tempFromPin1_.getVoltage();
        			System.out.println(getVoltage1);
        			getVoltage2=tempFromPin2_.getVoltage();
        			getVoltage3=tempFromPin3_.getVoltage();
        			getVoltage4=tempFromPin4_.getVoltage();
        			getVoltage5=tempFromPin5_.getVoltage();
        		}catch (InterruptedException e){
        			tempFromPin1_.close();
        			tempFromPin2_.close();
        			tempFromPin3_.close();
        			tempFromPin4_.close();
        			tempFromPin5_.close();
        			e.printStackTrace();
        		}
        		temp1=((getVoltage1*1024)-500)/10;
        		temp2=((getVoltage2*1024)-500)/10;
        		temp3=((getVoltage3*1024)-500)/10;
        		temp4=((getVoltage4*1024)-500)/10;
        		temp5=((getVoltage5*1024)-500)/10;
        		
        		float[] templist = new float[5];
        		templist[0]=temp1;
        		templist[1]=temp2;
        		templist[2]=temp3;
        		templist[3]=temp4;
        		templist[4]=temp5;
        		
        		float MaxTemp = templist[0];
        		for (int i=1;i<templist.length;i++){
        			if (MaxTemp<templist[i]){
        				MaxTemp = templist[i];
        			}
        				
        		}
        		maxTemptemp = MaxTemp;
        		
        		runOnUiThread(new Runnable() {
					
					@Override
					public void run() {
						/*
						 * Alarm activated if boolean is true and temperature is more than 37
						 */

			            if (tempboo==true & maxTemptemp>37){ 
			    			startAlarm();
			    			AlertDialog alertDialog = new AlertDialog.Builder(
			                        MainActivity.this).create();
			    			// Dialog Title
			    			alertDialog.setTitle("Smart Pillow Alert");

			    			// Dialog message
			    			alertDialog.setMessage("Warning! Temperature is beyond normal body temperature!");

			    			// Icon for Dialog
			    			alertDialog.setIcon(R.drawable.mark);

			    			// Setting OK Button
			    			alertDialog.setButton("OK",
			    					new DialogInterface.OnClickListener() {

			    						public void onClick(DialogInterface dialog,
			    								int which) {
			    							//dialog after alarm has started
			    							stopAlarm();
			    							Toast.makeText(getApplicationContext(),
			    									"Alarm has been stopped...", Toast.LENGTH_SHORT)
			    									.show();
			    						}
			    					});

			    			//show alert message
			    			alertDialog.show();

			    		}
			           	
			    		if (tempboo==false){
			           		//tempboo=true;
			           		alarmDisplay.setText("Alarm is off");
			           		}
			           		else if(tempboo==true){
			           			//tempboo=false;
			           			alarmDisplay.setText("Alarm is on");
			           		}
						
						
						tempDisplay.setText(Float.toString(maxTemptemp));
						// TODO Auto-generated method stub
						
						


						
					}
				});
        	}
        	
        	
        }
        
        
       	@SuppressWarnings("deprecation")
       	
       	
       	
       	
    		
       	public void onClick(View v) {
       		if (tempboo==false){
       		tempboo=true;
       		//alarmDisplay.setText("Alarm is on");
       		}
       		else if(tempboo==true){
       			tempboo=false;
       			//alarmDisplay.setText("Alarm is off");
       		}
       	}

        	//}
        	public void startAlarm() {
        		/**
        		 * call broadcost reciver
        		 */
        		Calendar calendar = Calendar.getInstance();
        		calendar.setTimeInMillis(System.currentTimeMillis());
        		alarm.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000, pendingIntent);
        		
        		
        	}
        	public void stopAlarm(){
        				tempboo=false;
        				alarm.cancel(pendingIntent);
        		
        		
        		
        	}

        
		@Override
		protected IOIOLooper createIOIOLooper() {
			// TODO Auto-generated method stub
			return new Looper();
		}

		//@Override
		//public void onClick(View v) {
			// TODO Auto-generated method stub
			
		//}
		
        
        
        
           
}
